<script setup lang="ts">
  import { throttle } from 'lodash-es';
  import { Select, CloseBold, Search, Refresh, Sort } from '@element-plus/icons-vue';
  import { GetTable, commpandGive, commpandRemove } from '@/api/commandPages';
  import { splitShowDialog } from './index';
  //   getDatalist, saveData, deleteTableList
  const TablesData = ref<any>();
  interface state {
    tableData: Array<Namespace.commandTable>;
    total: number;
    pageSize: number;
    currentPage: number;
    filterTableData: any[];
    MultiSelectData: Array<Namespace.commandTable>;
    loading: boolean;
  }
  const props = defineProps({
    rightTreeData: {
      type: Object,
    },
    regionCode: {
      type: Number,
    },
    data: {
      type: Object,
    },
  });
  const state: state = reactive({
    tableData: [],
    total: 0,
    pageSize: 10,
    currentPage: 1,
    filterTableData: [],
    MultiSelectData: [],
    loading: false,
  });
  const searchKey = reactive<{
    unit_code: string;
    unit_name: string;
    type: string;
    code: string;
    name: string;
  }>({
    unit_code: '',
    unit_name: '',
    type: '',
    code: '',
    name: '',
  });
  watch(
    () => props.rightTreeData,
    async (value: any) => {
      if (value && props.data) {
        state.loading = true;
        try {
          const { data } = await GetTable({ id: props.data.dataId.id, unitId: value.id });
          state.tableData = data;
          state.filterTableData = data;
          state.total = state.tableData.length;
          state.currentPage = 1;
          state.pageSize = 10;
          searchKey.unit_code = '';
          searchKey.unit_name = '';
          searchKey.type = '';
          searchKey.code = '';
          searchKey.name = '';
        } catch {
          state.loading = false;
        }
        state.loading = false;
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  const handleSizeChange = (value: number) => {
    state.currentPage = 1;
    state.pageSize = value;
  };
  const handleCurrentChange = (value: number) => {
    state.currentPage = value;
  };
  const handelGiveOdd = throttle(async (row) => {
    if (row.id) {
      const dataList = {
        id: row.id,
        unit_id: row.unit_id,
      };
      const dataObj = {
        id: props.data?.dataId.id,
        unitData: JSON.stringify([dataList]),
      };
      const { code } = await commpandGive(dataObj);
      if (code === 0) {
        state.loading = true;
        try {
          const { data } = await GetTable({
            id: props.data?.dataId.id,
            unitId: props.rightTreeData?.id,
          });
          state.tableData = data;
          state.filterTableData = data;
          state.total = state.tableData.length;
          state.currentPage = 1;
          state.pageSize = 10;
        } catch {
          state.loading = false;
        }
        state.loading = false;
      }
    }
  });
  const handleGive = throttle(async () => {
    if (!state.MultiSelectData.length) {
      ElMessage.error('请选择数据！');
      return;
    }
    const dataList = state.MultiSelectData.map((item) => {
      return {
        id: item.id,
        unit_id: item.unit_id,
      };
    });
    const dataObj = {
      id: props.data?.dataId.id,
      unitData: JSON.stringify(dataList),
    };
    const { code } = await commpandGive(dataObj);
    if (code === 0) {
      state.loading = true;
      try {
        const { data } = await GetTable({
          id: props.data?.dataId.id,
          unitId: props.rightTreeData?.id,
        });
        state.tableData = data;
        state.filterTableData = data;
        state.total = state.tableData.length;
        state.currentPage = 1;
        state.pageSize = 10;
      } catch {
        state.loading = false;
      }
      state.loading = false;
    }
  });
  const handleRemove = throttle(async () => {
    if (!state.MultiSelectData.length) {
      ElMessage.error('请选择数据！');
      return;
    }
    const dataList = state.MultiSelectData.map((item) => {
      return item.r_id as number;
    });
    const { code } = await commpandRemove({ rId: dataList });
    if (code === 0) {
      state.loading = true;
      try {
        const { data } = await GetTable({
          id: props.data?.dataId.id,
          unitId: props.rightTreeData?.id,
        });
        state.tableData = data;
        state.filterTableData = data;
        state.total = state.tableData.length;
        state.currentPage = 1;
        state.pageSize = 10;
      } catch {
        state.loading = false;
      }
      state.loading = false;
    }
  });
  const handleRemoveOdd = throttle(async (row) => {
    const { code } = await commpandRemove({ rId: [row.r_id] });
    if (code === 0) {
      state.loading = true;
      try {
        const { data } = await GetTable({
          id: props.data?.dataId.id,
          unitId: props.rightTreeData?.id,
        });
        state.tableData = data;
        state.filterTableData = data;
        state.total = state.tableData.length;
        state.currentPage = 1;
        state.pageSize = 10;
      } catch {
        state.loading = false;
      }
      state.loading = false;
    }
  });
  const sendGrandsonComIds = inject('sendHandleComIds') as Function;
  const handleSplit = throttle(async () => {
    if (!state.MultiSelectData.length) {
      ElMessage.error('请选择数据！');
      return;
    }
    const data = state.MultiSelectData.map((item) => item.r_id);
    splitShowDialog.value = true;
    sendGrandsonComIds(data);
  });
  const handleSelectionChange = async (value: Array<Namespace.commandTable>) => {
    state.MultiSelectData = value;
  };
  const handleKey = async () => {
    const hasSearchKeys = Object.values(searchKey).some((key) => key.trim() !== '');

    // 预处理数据：将所有为 null 的字段转为空字符串
    const processedFilterTableData = state.filterTableData.map((item) => {
      const processedItem = {};
      for (const key in item) {
        processedItem[key] = item[key] === null ? '' : item[key];
      }
      return processedItem;
    });

    if (hasSearchKeys) {
      state.tableData = processedFilterTableData.filter((item) => {
        return Object.entries(searchKey).every(([key, value]) => {
          const propertyValue = item[key];

          if (key === 'type') {
            // 将 searchKey 中的 type 字段转换为数字进行比较
            return propertyValue === Number(value);
          } else {
            // 对于其他字段，进行字符串匹配
            return (
              (typeof propertyValue === 'string' || typeof propertyValue === 'number') &&
              propertyValue.toString().includes(value)
            );
          }
        });
      }) as Namespace.commandTable[];
    } else {
      state.loading = true;
      try {
        const { data } = await GetTable({
          id: props.data?.dataId.id,
          unitId: props.rightTreeData?.id,
        });
        state.tableData = data;
        state.filterTableData = data;
        state.total = state.tableData.length;
        state.currentPage = 1;
        state.pageSize = 10;
      } catch {
        state.loading = false;
      }
      state.loading = false;
    }

    state.total = state.tableData.length;
    state.currentPage = 1;
    state.pageSize = 10;
  };

  const handleRefresh = async () => {
    searchKey.unit_code = '';
    searchKey.unit_name = '';
    searchKey.type = '';
    searchKey.code = '';
    searchKey.name = '';
    state.loading = true;
    try {
      const { data } = await GetTable({
        id: props.data?.dataId.id,
        unitId: props.rightTreeData?.id,
      });
      state.tableData = data;
      state.total = state.tableData.length;
      state.filterTableData = data;
      state.currentPage = 1;
      state.pageSize = 10;
    } catch {
      state.loading = false;
    }
    state.loading = false;
  };
</script>

<template>
  <div class="table_content">
    <div class="table_content_search">
      <div class="search">
        <ElForm :model="searchKey" :label-width="80">
          <ElRow>
            <ElCol :span="12">
              <ElFormItem label="单元编号">
                <ElInput v-model="searchKey.unit_code" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="12">
              <ElFormItem label="单元名称">
                <ElInput v-model="searchKey.unit_name" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="类型">
                <ElSelect v-model="searchKey.type" clearable filterable>
                  <ElOption label="单元权限" value="0" />
                  <ElOption label="元素权限" value="1" />
                  <ElOption label="数据权限" value="2" />
                  <ElOption label="app元素权限" value="3" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="编号">
                <ElInput v-model="searchKey.code" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="名字">
                <ElInput v-model="searchKey.name" />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </div>
      <div class="button">
        <ElButton type="primary" :icon="Search" @click="handleKey">查询</ElButton>
        <ElButton type="info" :icon="Refresh" @click="handleRefresh">重置</ElButton>
        <ElButton type="primary" :icon="Select" @click="handleGive">赋予权限</ElButton>
        <ElButton type="danger" :icon="CloseBold" @click="handleRemove">移除权限</ElButton>
        <ElButton
          type="primary"
          :icon="Sort"
          @click="handleSplit"
          v-if="props.rightTreeData?.id == 0"
          >拆分权限</ElButton
        >
      </div>
    </div>
    <div class="table_content_tables">
      <ElTable
        ref="TablesData"
        :data="
          state.tableData.slice(
            (state.currentPage - 1) * state.pageSize,
            state.currentPage * state.pageSize,
          )
        "
        style="width: 100%"
        height="calc(100vh - 134px - 100px)"
        border
        table-layout="fixed"
        @selection-change="handleSelectionChange"
        v-loading="state.loading"
      >
        <ElTableColumn type="selection" width="55" />
        <ElTableColumn label="操作" width="120">
          <template #default="scope">
            <ElButton type="primary" v-if="scope.row.state == 0" @click="handelGiveOdd(scope.row)"
              >赋予权限</ElButton
            >
            <ElButton type="danger" v-else @click="handleRemoveOdd(scope.row)">移除权限</ElButton>
          </template>
        </ElTableColumn>
        <ElTableColumn label="单元编号" prop="unit_code" width="200" />
        <ElTableColumn label="单元名称" prop="unit_name" width="180" />
        <ElTableColumn label="类型" width="100">
          <template #default="scope">
            <span
              :style="{
                backgroundColor:
                  scope.row.type === 0
                    ? '#409eff'
                    : scope.row.type === 1
                    ? '#e6a23c'
                    : scope.row.type === 2
                    ? '#67c23a'
                    : scope.row.type === 3
                    ? 'rgb(210, 42, 176)'
                    : '',
                width: '80px',
                height: '25px',
                lineHeight: '25px',
                textAlign: 'center',
                display: 'block',
                color: '#FFF',
              }"
              >{{
                scope.row.type === 0
                  ? '单元权限'
                  : scope.row.type === 1
                  ? '元素权限'
                  : scope.row.type === 2
                  ? '数据权限'
                  : scope.row.type === 3
                  ? 'app元素权限'
                  : ''
              }}</span
            >
          </template>
        </ElTableColumn>
        <ElTableColumn label="编号" prop="code" width="200" />
        <ElTableColumn label="名字" prop="name" width="180" />
        <ElTableColumn label="数据权限SQL" prop="sql_permissions" width="300" />
      </ElTable>
      <div style="margin-top: 20px">
        <ElPagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="state.currentPage"
          :page-sizes="[1, 5, 10, 20]"
          background
          :page-size="state.pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="state.total"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .table_content {
    padding: 20px 20px 0 20px;
    height: $height;
    &_tables {
      &_search {
        display: flex;
        flex-direction: row;
        align-items: center;
        .button {
          margin-left: 50px;
          :deep(.el-button) {
            height: 38px;
          }
        }
      }
      padding-top: 20px;
      :deep(th) {
        color: #000;
        background-color: rgba(9, 96, 189, 0.05);
        background-image: linear-gradient(rgba(9, 96, 189, 0.1), #fff);
      }
      :deep(.el-radio) {
        margin-right: 15px;
      }
      :deep(.el-radio:last-child) {
        margin-right: 0;
      }
      :deep(.el-radio--large) {
        height: 25px;
      }
    }
  }
</style>
